﻿export function obj2formdata(object) {
  return Object.keys(object).reduce((formData, key) => {
    if (typeof object[key] === "object") {
      formData.append(key, JSON.stringify(object[key]));
    } else {
      formData.append(key, object[key]);
    }
    return formData;
  }, new FormData());
}
export function copyValue(str) {
  // Create new element
  var el = document.createElement('textarea');
  // Set value (string to be copied)
  el.value = str;
  // Set non-editable to avoid focus and move outside of view
  el.setAttribute('readonly', '');
  el.style = {
    position: 'absolute',
    left: '-9999px'
  };
  document.body.appendChild(el);
  // Select text inside element
  el.select();
  // Copy text to clipboard
  document.execCommand('copy');
  // Remove temporary element
  document.body.removeChild(el);
  if (str.length > 0) {
    return true;
  }
}

// 下载文件
export function saveAs(uri, params, filename) {
  var link = document.createElement('a');
  if (typeof link.download === 'string') {
    document.body.appendChild(link); // Firefox requires the link to be in the body
    link.download = filename;
    var href = '';
    if (params) {
      href = '?' + obj2params(params);
    } else {
      href = '';
    }
    link.href = uri + href;
    link.click();
    document.body.removeChild(link);
  } else {
    location.replace(uri);
  }
}

// 直接下载文件，而不是打开预览
export function downloadUrlFile(url, name) {
  url = url.replace(/\\/g, '/');
  const xhr = new XMLHttpRequest();
  xhr.open('GET', url, true);
  xhr.responseType = 'blob';
  //xhr.setRequestHeader('Authorization', 'Basic a2VybWl0Omtlcm1pdA==');
  xhr.onload = () => {
    // console.log('xhr: ', xhr);
    if (xhr.status === 200) {
      // 获取文件blob数据并提交
      saveAs1(xhr.response, name);
    }
  };

  xhr.send();
}
function saveAs1(data, name) {
  var urlObject = window.URL || window.webkitURL || window;
  var export_blob = new Blob([data]);
  var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
  save_link.href = urlObject.createObjectURL(export_blob);
  save_link.download = name;
  save_link.click();
}

/*
  正则表达式，匹配只输出整数或者浮点数
  value:传入的值
*/
export function numberReg(value) {
  const m = value.replace(/[^0-9.]/g, "")
    .replace(".", "#*")
    .replace(/\./g, "")
    .replace("#*", ".");
  return m;
}

// 角色树形结构，获取check为true的所有菜单的ID数组,不包含func内子集
export function getCheckedId(obj, arr = []) {
  obj.check && arr.push(obj.id);
  if (obj.children !== undefined) {
    obj.children.forEach(item => {
      getCheckedId(item, arr);
    });
  }
  return arr;
}
// 获取func被选中的id数组
export function getCheckedFuncId(obj, idArr) {
  var arr1 = [];
  if (idArr.includes(obj.id)) {
    if (obj.func) {
      obj.func.map(item => {
        if (item.check) {
          arr1.push(item.id);
        }
      })
    } else {
      var arr2 = []
      obj.children.forEach(item => {
        arr2 = arr2.concat(getCheckedFuncId(item, idArr));
      })
    }
  }
  return arr1.concat(arr2 || []);
}
// 字符串千分位处理
export function modifyMoney(value) {
  var num_parts = value.toString().split(".");
  if (num_parts[0] === "0") {
    return "0.00"
  } else if (num_parts[0] === "") {
    return "";
  }
  if (isNaN(num_parts[0])) {
    return value;
  }
  num_parts[0] = num_parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  if (num_parts.length === 1) {
    return num_parts.join(".") + ".00";
  } else {
    if (num_parts[1].length === 1) {
      return num_parts.join(".") + "0";
    } else if (num_parts[1].length === 2) {
      return num_parts.join(".");
    } else {
      num_parts[1] = num_parts[1].slice(0, 2);
      return num_parts.join(".");
    }
  }
}

// 千位计数法改为普通数字
export function getNormalNum(value) {
  if (typeof value === "string") {
    return parseFloat(value.split(",").join(""));
  }
  return value;
}

// 获取类型
export function getType(text) {
  if (typeof text !== "string") return;
  switch (true) {
    case text.includes("竣工"):
    case text.includes("是"):
    case text.includes("正常"):
    case text.includes("现金"):
      return "success";
    case text.includes("在建"):
    case text.includes("保函"):
    case text.includes("初始化"):
      return "primary";
    case text.includes("未开工"):
    case text.includes("否"):
    case text.includes("停用"):
    case text.includes("禁用"):
    case text.includes("销毁"):
      return "danger";
    case text.includes("全部"):
    case text.includes("审核中"):
      return "warning";
    default:
      return "info";
  }
}
//  object to url params
export function obj2params(obj) {
  var str = "";
  for (var key in obj) {
    if (str != "") {
      str += "&";
    }
    str += key + "=" + encodeURIComponent(obj[key]);
  }
  return str;
}
export function getfilesize(size) {
  if (!size) { return ""; }

  var num = 1024.00; // byte

  if (size < num) { return size + "B"; }
  if (size < Math.pow(num, 2)) { return (size / num).toFixed(2) + "K"; } // kb
  if (size < Math.pow(num, 3)) { return (size / Math.pow(num, 2)).toFixed(2) + "M"; } // M
  if (size < Math.pow(num, 4)) { return (size / Math.pow(num, 3)).toFixed(2) + "G"; } // G
  return (size / Math.pow(num, 4)).toFixed(2) + "T"; // T
}

// 获取当前年月日的第一天到最后一天
export function getYearMnothDate(params) {
  let date = new Date();
  let year = date.getFullYear();
  let month = date.getMonth() + 1;
  let tempmonth = month.toString()[1] ? month : '0' + month;
  let day = date.getDate();
  let tempday = day.toString()[1] ? day : '0' + day;
  let lastDay = new Date(year, tempmonth, 0).getDate();
  // console.log('year: ', year,tempmonth,tempday,lastDay);
  return [year + '-' + month + '-' + '01', year + '-' + month + '-' + lastDay];
}

// 对象数组升序函数:property:属性名，属性值为数字类型
export function compare(property) {
  return function (obj1, obj2) {
    var value1 = obj1[property];
    var value2 = obj2[property];
    return value1 - value2;
  }
}

// 比较两个数组，以第一个数组为主，移除重复的对象
export function compareArray(arr1, key, arr2) {
  let list = arr2.map(v => v[key]);
  let data = arr1.filter(v => !list.includes(v[key]));
  return data;
}

// 利用数组reduce方法对数组对象去重
export function reduceDuplication(arr,key) {
  let hash = {};
  var newArr = arr.reduce((item, next) => {
    hash[next[key]] ? '' : hash[next[key]] = true && item.push(next);
    return item
  }, []);
  console.log(newArr);
  return newArr;
}